package core
{
	import core.events.PutIoErrorEvent;
	import core.events.PutIoResultEvent;
	
	import flash.events.Event;

	public class PutIoLoaderManager
	{
		private static var instance:PutIoLoaderManager;
		private static var allowInstance:Boolean = false;		
		
		private var putIoLoaderList:PutIoLoaderList = new PutIoLoaderList();
		
		/**
		 * This class implement the Singleton pattern so direct instance is not allowed.
		 * <br />
		 * To get an instance, use getInstance() method
		 * 
		 * @see getInstance
		 */		
		public function PutIoLoaderManager() {
			if(!allowInstance)
				throw new Error('Multiple instance not allowed in PutIoLoaderManager class !');			
		}		
		
		/**
		 * Get the unique instance of this class
		 * 
		 * @return the unique instance
		 */		
		public static function getInstance():PutIoLoaderManager {
			if(instance == null) {
				allowInstance = true;
				instance = new PutIoLoaderManager();
				allowInstance = false;
			}
			
			return instance;
		}	
		
		/**
		 * Initiating a Put.io request
		 * 
		 * @param category Class to call (ex: files, messages, transfers, urls, user, subscription)
		 * @param method Class method to call (ex: list, add, cancel for transfers category)
		 * @param result Function to call if put.io returns a correct result
		 * @param error Function to call if put.io returns an error
		 * @param parameters Parameters to send
		 */
		public function initiatingConnection(category:String, method:String, result:Function, 
											 error:Function = null, parameters:Object = null):String
		{
			var loader:PutIoLoader = new PutIoLoader(category, method, parameters);
			
			loader.addEventListeners(result, error);
			loader.addEventListeners(onResult, onError);
			
			var loaderId:String = putIoLoaderList.addLoader(loader);
			
			return loaderId;
		}
		
		/**
		 * Send the request to Put.io
		 * 
		 * @param id Id of connection
		 */				
		public function load(loaderId:String):void
		{
			var loader:PutIoLoader = putIoLoaderList.getLoader(loaderId);
			loader.load();
		}

		/**
		 * Cancel a request
		 * 
		 * @param id Id of connection
		 */				
		public function cancel(loaderId:String):void
		{
			var loader:PutIoLoader = putIoLoaderList.getLoader(loaderId);
			loader.cancel();
		}
		
		private function onResult(event:PutIoResultEvent):void
		{
			putIoLoaderList.removeLoader(event.loaderId);
		}
		
		private function onError(event:PutIoErrorEvent):void
		{
			putIoLoaderList.removeLoader(event.loaderId);
		}

	}
}